// pages/opening-address/address.js


const QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;

qqmapsdk = new QQMapWX({
  key: 'GQCBZ-FUGO5-ZXQII-QU65G-7IRP2-SUFNN'
});

import {
  ajax,
  src,
  util
} from "../../utils/util.js";

const app = getApp();
var top = app.globalData.navTop;
var isIphoneX = app.globalData.isIphoneX;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: isIphoneX,
    // top:top+70+'px',  //分享
    navTop: top,

    dataId: "0-0",
    fenxiang:false,
    showhaibao:false,
    haibaourl: '',

    // 0 定位了未开通   1 未定位   2 重新选择
    status:0,
    allopenaddress:""
  },
  // 生成海报
  creathaibao: function () {
    ajax('/api/PosterPictures/Get?requestContent=' + JSON.stringify({

      token: wx.getStorageSync("Access_token")
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        console.log(res)
        this.setData({
          haibaourl: res.Models[0].ImgUrl,
          fenxiang: false,
          showhaibao: true,
        })

      })
  },
  // 退出海报
  tuichuhaibaofx: function () {
    this.setData({
      showhaibao: false,
    })
  },
  postSave(e) {
    wx.showLoading({
      title: '保存中...'
    })
    wx.downloadFile({
      url: this.data.haibaourl,
      success: function (res) {
        //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            wx.hideLoading()
            wx.showModal({
              title: '提示',
              content: '您的推广海报已存入手机相册，赶快分享给好友吧',
              showCancel: false,
            })
          },
          fail: function (err) {
            if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
              wx.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                showCancel: false,
                success: modalSuccess => {
                  wx.openSetting({
                    success(settingdata) {
                      console.log("settingdata", settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限成功,再次点击图片即可保存',
                          showCancel: false,
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限失败，将无法保存到相册哦~',
                          showCancel: false,
                        })
                      }
                    },
                    fail(failData) {
                      console.log("failData", failData)
                    },
                    complete(finishData) {
                      console.log("finishData", finishData)
                    }
                  })
                }
              })
            }
          },
          complete(res) {
            wx.hideLoading()
          }
        })
      }
    })
  },

  loadCity: function (longitude, latitude) {
    var that = this;
    // 获取经度纬度
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: (res) => {
        console.log(res)
        console.log("11111111111111")

        if (res.status == 0) {
          var address_component = res.result.address_component;
          var address
          // var areaName = city.replace(/省|市|自治区|特别行政区|壮族|回族|维吾尔/g, "");
          // 保存在本地
          if (res.result.address_component.province == res.result.address_component.city) {
            address = res.result.address_component.city + res.result.address_component.district
          } else {
            address = res.result.address_component.province + res.result.address_component.city + res.result.address_component.district
          }


          // that.setaddress(address)

          wx.setStorageSync('address_component', address_component);
          wx.setStorageSync('address', address);

          wx: wx.setStorageSync('currentaddress', address_component.district)

          wx.setStorageSync('formatted_addresses', res.result.formatted_addresses.recommend);

          wx.setStorageSync('formatted_addressescopy', res.result.formatted_addresses.recommend);

          this.setData({
            formatted_addresses: res.result.formatted_addresses.recommend
          })

          // this.panduaniskaitong()
        }
      }
    })
  },

  //  获取经度纬度
  getaddress: function () {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy

        wx.setStorageSync("latitude", latitude)
        wx.setStorageSync("longitude", longitude)
        this.loadCity(longitude, latitude)
        // console.log("sssss")
      },
      fail: () => {
        this.setData({
          showaddresstc: true
        })
      }
    })
  },

  // 分享框
  shareclick: function () {
    this.setData({
      fenxiang: true
    });
  },

  // 取消分享事件
  quxiao: function () {
    this.setData({
      fenxiang: false
    });
  },
  // 定位地址的选择
  posi:function(e){
    console.log(e)
    var idx = e.currentTarget.dataset.id;
    this.setData({
      dataId: idx
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000',
    })
    var status = options.status
    var nogps = options.nogps
    this.setData({
      status: status
    })
    if (nogps){
      this.setData({
        iskaitong: true,
        nogps:nogps
      })
      // wx.setStorageSync("nogps", 1)
    }

  },

  getallopenaddress: function () {
    ajax('/api/RegionShop/Get?requestContent=' + JSON.stringify({
      ProvinceName: "",
      CityName: "",
      DistrictName: ""
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {

        console.log(res)
        var allopenaddress=[]
       
        for (var x in res.Models){
          if(x==0){
            var obj = {}
            var obj1 = {}
            obj.ProvinceName = res.Models[x].ProvinceName
            obj.Citylist = []
            obj1.CityName = res.Models[x].CityName
            obj1.Districtlist = []
            obj1.Districtlist.push(res.Models[x].DistrictName)
            obj.Citylist.push(obj1)
            allopenaddress.push(obj)
          }else{
            var flage=1
            for (var y in allopenaddress) {
              if (allopenaddress[y].ProvinceName == res.Models[x].ProvinceName) {
                flage=0
                // allopenaddress[y].Districtlist.push(res.Models[x].DistrictName)
                for (var z in allopenaddress[y].Citylist) {
                  if (allopenaddress[y].Citylist[z].CityName == res.Models[x].CityName) {
                    allopenaddress[y].Citylist[z].Districtlist.push(res.Models[x].DistrictName)

                    // if (allopenaddress[y].Citylist[z].Districtlist.indexof(res.Models[x].DistrictName) > -1) {
                    //   break
                    // } else {
                    //   allopenaddress[y].Citylist[z].Districtlist.push(res.Models[x].DistrictName)
                    // }

                  } else {
                    var obj1 = {}
                    obj1.CityName = res.Models[x].cityname
                    obj1.Districtlist = []
                    obj1.Districtlist.push(res.Models[x].DistrictName)

                    allopenaddress[y].Citylist.push(obj1)
                  }
                }
              } 
            }
            if(flage==1){
              var obj = {}
              var obj1 = {}
              obj.ProvinceName = res.Models[x].ProvinceName
              obj.Citylist = []

              obj1.CityName = res.Models[x].CityName
              obj1.Districtlist = []
              obj1.Districtlist.push(res.Models[x].DistrictName)
              obj.Citylist.push(obj1)
              allopenaddress.push(obj)
            }
          }

          

          
          // var canfor = allopenaddress.splice(allopenaddress.length-1, 1)
          console.log(allopenaddress)
          this.setData({
            allopenaddress: allopenaddress
          })
        }

      })

  },
  select:function(e){
    var str = e.currentTarget.dataset.id;
    var indexlist = str.split('-')

    console.log(indexlist)
    var address_component={}
    var address

    // { "nation": "中国", "province": "北京市", "city": "北京市", "district": "海淀区", "street": "长春桥路", "street_number": "长春桥路17号" }
    address_component.province = this.data.allopenaddress[indexlist[0]].ProvinceName
    address_component.city = this.data.allopenaddress[indexlist[0]].Citylist[indexlist[1]].CityName
    address_component.district = this.data.allopenaddress[indexlist[0]].Citylist[indexlist[1]].Districtlist[indexlist[2]]

    if (this.data.allopenaddress[indexlist[0]].ProvinceName == this.data.allopenaddress[indexlist[0]].Citylist[indexlist[1]].CityName){
      address = this.data.allopenaddress[indexlist[0]].Citylist[indexlist[1]].CityName + this.data.allopenaddress[indexlist[0]].Citylist[indexlist[1]].Districtlist[indexlist[2]]
    }else{
      address = this.data.allopenaddress[indexlist[0]].ProvinceName+this.data.allopenaddress[indexlist[0]].Citylist[indexlist[1]].CityName + this.data.allopenaddress[indexlist[0]].Citylist[indexlist[1]].Districtlist[indexlist[2]]
    }
    
    wx.setStorageSync('address_component', address_component);
    wx.setStorageSync('address', address);

    // wx.setStorageSync('latitude', "");
    // wx.setStorageSync('longitude', "");
    var currentaddress = wx.getStorageSync('currentaddress')
    if (currentaddress){
      if (currentaddress == this.data.allopenaddress[indexlist[0]].Citylist[indexlist[1]].Districtlist[indexlist[2]]){
        
        var formatted_addressescopy = wx.getStorageSync('formatted_addressescopy')
        console.log(formatted_addressescopy)

        wx.setStorageSync('formatted_addresses', formatted_addressescopy);
      }else{
        wx.setStorageSync('formatted_addresses', "");
      }
    }else{
    }
    
    

    wx.reLaunch({
      url: '/pages/index/index',
    })
  },

  navBack: function () {
    wx.navigateBack({
      delta: 1
    })
  },
  //回主页
  toIndex: function () {
    console.log("aaaaaaaaaaaaa")
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    if(!this.data.nogps){
      if (this.data.status == 1) {
        var that = this
        wx.getSetting({
          success(res) {
            // console.log(res.authSetting["scope.userLocation"])
            // // res.authSetting = {
            // //   "scope.userInfo": true,
            // //   "scope.userLocation": true
            // // }
            var info = res.authSetting
            if (info["scope.userLocation"]) {
              that.setData({
                iskaitong: true
              })
              wx.reLaunch({
                url: '/pages/index/index',
              })
            }
          }
        })
      }

      if (this.data.status == 2) {
        var that = this
        wx.getSetting({
          success(res) {

            // console.log(res.authSetting["scope.userLocation"])
            // // res.authSetting = {
            // //   "scope.userInfo": true,
            // //   "scope.userLocation": true
            // // }


            console.log(res)

            var info = res.authSetting
            if (info["scope.userLocation"]) {

              that.getaddress()

              console.log("sssssss")
              that.setData({
                iskaitong: true
              })
            }
          }
        })
      }




      
    }
    this.getallopenaddress()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {

      title: '897便利购', //转发的标题

      path: `pages/index/index`,//转发的连接 后面带 id

      imageUrl: ''
    } //转发的图片

  }
})